package com.alex.common.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.HtmlUtils;

import com.alex.common.ILogger;
import com.alex.common.persistent.UserDao;
import com.alex.common.security.SimpleAuthor;
import com.alex.common.security.domain.User;
import com.alex.common.tools.CookieUtils;
import com.alex.common.tools.MD5Utils;

@Controller
@RequestMapping("/")
public class IndexController {

	@RequestMapping(value = "mda", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String tableview(Model model) {
		model.addAttribute("mdadmin", "mda");
		return "toolslib/tableview";
	}

	@RequestMapping(value = "rest", method = { RequestMethod.GET,
			RequestMethod.POST })
	public @ResponseBody
	String rest(Model model) {
		return "Hello rest!";
	}

	/********************* About *****************************/

	@RequestMapping(value = "about", method = { RequestMethod.GET })
	public String about(Model model) {
		return "about";
	}

	/********************* Login *****************************/

	private static final String LOGIN_FAILED = "Login failed.";

	private static final String LOGIN_OK = "Login OK.";

	private static final String LOGIN_OUT = "Login out.";

	@Autowired
	private UserDao userDao;

	@RequestMapping(value = "login", method = { RequestMethod.GET })
	public String login(Model model, HttpServletRequest request) {
		String ref = request.getParameter("ref");
		if (ref != null && !"".equals(ref)) {
			model.addAttribute("ref", ref);
		}
		return "login";
	}

	@RequestMapping(value = "login_submit", method = { RequestMethod.POST })
	public ModelAndView login_submit(@RequestParam("userpass") String userpass,
			@RequestParam("ref") String ref, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		CookieUtils cookie = new CookieUtils(request, response);
		String msg = LOGIN_FAILED;
		if (userpass != null && userpass.split(" ").length == 2) {
			String[] user_pass = userpass.split(" ");
			String userTicket = new StringBuilder(user_pass[0]).append(" ")
					.append(MD5Utils.getMD5DigestHex(user_pass[1])).toString();
			User user = userDao.find(user_pass[0]);

			if (user != null && user.getTicket().equals(userTicket)) {
				{
					// set username and authority to session
					request.getSession().setAttribute(SimpleAuthor.S_USERNAME,
							user.getUsername());
					request.getSession().setAttribute(SimpleAuthor.S_AUTHORITY,
							user.getAuthority());
				}

				// 30 days cookie
				cookie.add(SimpleAuthor.S_COOKIE_TICKET, user.getTicket(),
						60 * 60 * 24 * 30);

				msg = LOGIN_OK;
				ILogger.logger_common.info(LOGIN_OK + " " + user_pass[0]);
			} else {
				// kill cookie
				cookie.delete(SimpleAuthor.S_COOKIE_TICKET);
				ILogger.logger_common.info(LOGIN_FAILED + " " + user_pass[0]);
			}
		} else {
			ILogger.logger_common.info(LOGIN_FAILED);
		}

		String gotourl = "/";
		if (ref != null && !"".equals(ref)) {
			gotourl = HtmlUtils.htmlUnescape(ref);
		}
		// TODO using popup
		ModelAndView mv = new ModelAndView(new RedirectView(gotourl), "msg",
				msg);
		return mv;
	}

	@RequestMapping(value = "logout", method = { RequestMethod.GET })
	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		CookieUtils cookie = new CookieUtils(request, response);

		// kill cookie
		cookie.delete(SimpleAuthor.S_COOKIE_TICKET);
		// kill session
		request.getSession().removeAttribute(SimpleAuthor.S_AUTHORITY);
		request.getSession().removeAttribute(SimpleAuthor.S_USERNAME);

		ModelAndView mv = new ModelAndView(new RedirectView("/"), "msg",
				LOGIN_OUT);
		return mv;
	}

	/********************* Login over *****************************/
}
